package com.parking.carsystem.parkingchargesystem.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.EnvUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.module.AbsenceData;
import com.parking.carsystem.parkingchargesystem.module.GroupListModule;
import com.parking.carsystem.parkingchargesystem.module.LatlngModule;
import com.parking.carsystem.parkingchargesystem.module.ListRuleModel;
import com.parking.carsystem.parkingchargesystem.module.PayMouthModel;
import com.parking.carsystem.parkingchargesystem.utils.TimeUtil;
import com.parking.carsystem.parkingchargesystem.view.BottomDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import ttyy.com.recyclerexts.base.EXTRecyclerAdapter;
import ttyy.com.recyclerexts.base.EXTViewHolder;

public class MonthlySubscriptionActivity extends BaseActivity implements View.OnClickListener, BottomDialog.ChooseTextLisenter {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.setting)
    TextView setting;
    @BindView(R.id.check_pay_record)
    TextView checkPayRecord;
    @BindView(R.id.add_parking)
    TextView addParking;
    @BindView(R.id.parking_car)
    TextView parkingCar;
    @BindView(R.id.parking_name)
    TextView parkingName;
    @BindView(R.id.choose_parking)
    TextView chooseParking;
    @BindView(R.id.start_time)
    TextView startTime;
    @BindView(R.id.end_time)
    TextView endTime;
    @BindView(R.id.pay_immediate_purchase)
    TextView payImmediatePurchase;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.title_bg)
    RelativeLayout titleBg;
    @BindView(R.id.palte_number_left)
    TextView palteNumberLeft;
    @BindView(R.id.parking_platenumber)
    TextView parkingPlatenumber;
    @BindView(R.id.package_left)
    TextView packageLeft;
    @BindView(R.id.parking_package)
    TextView parkingPackage;
    @BindView(R.id.choose_package)
    TextView choosePackage;
    @BindView(R.id.time_left)
    TextView timeLeft;
    @BindView(R.id.choose_time)
    TextView chooseTime;
    @BindView(R.id.layout_message)
    LinearLayout layoutMessage;
    //    private ArrayList<AbsenceData> absenceData;
//    private BottomDialog bottomDialog;
    private ArrayList<AbsenceData> parkingNameList;
    private AbsenceData tempAbsenceData;
    private ListRuleModel.RowsBean temRowsBean;
    private List<ListRuleModel.RowsBean> listruleList;
    private int parkinglotId;
    private ArrayList<AbsenceData> absenceDataPay;
    private ArrayList<AbsenceData> addParkingData;
    private ArrayList<AbsenceData> parkingLotData;
    private ArrayList<AbsenceData> packageData;
    private BottomDialog bottomDialogPay;
    private BottomDialog bottomDialogAddparking;
    private BottomDialog bottomDialogParkingLot;
    private BottomDialog bottomDialogPackage;
    private PayMouthModel payMouthModel;
    public int type;
    public int packageId;
    private String parkingPlatenumberName;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_subscription;
    }

    @Override
    public void initView() {
        //支付宝的开启沙箱环境支付
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        text.setText("我的月卡");
        startTime.setText(TimeUtil.getYMDString());
        endTime.setText(TimeUtil.getNextMounth());
        back.setVisibility(View.VISIBLE);
        chooseParking.setOnClickListener(this);
        addParking.setOnClickListener(this);
//        startTime.setOnClickListener(this);
        endTime.setOnClickListener(this);
        payImmediatePurchase.setOnClickListener(this);
        checkPayRecord.setOnClickListener(this);
        choosePackage.setOnClickListener(this);
        chooseTime.setOnClickListener(this);
    }

    @Override
    public void initData() {
        //支付的弹窗
        absenceDataPay = new ArrayList<>();
        absenceDataPay.add(new AbsenceData("支付宝", false));
        absenceDataPay.add(new AbsenceData("微信", false));
//        absenceDataPay.add(new AbsenceData("账户余额", false));
        bottomDialogPay = new BottomDialog(absenceDataPay.size(), this, 1);
        bottomDialogPay.setChooseTextLisenter(this);
        bottomDialogPay.setTitle("支付方式");
        bottomDialogPay.setBottomTitle("确认支付");
        bottomDialogPay.setBottomData(absenceDataPay);
        //添加车牌
        addParkingData = new ArrayList<>();
        //添加停车场
        parkingLotData = new ArrayList<>();
        //选择套餐
        packageData = new ArrayList<>();
        if (parkingNameList == null) {
            parkingNameList = new ArrayList<>();
        }
        getMemberListRule();
        listParkingLot();
        getGroupList();
    }

    /**
     * 获取套餐信息
     */
    private void getMemberListRule() {
        OkGo.<String>get(Constant.url + Constant.MEMBERLISTRULE)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ListRuleModel listRuleModel = gson.fromJson(response.body(), ListRuleModel.class);
                        if (listRuleModel.code == 200) {
                            for (ListRuleModel.RowsBean row : listRuleModel.rows) {
                                packageData.add(new AbsenceData(String.valueOf(row.month + "个月"), false, row.id, row.month, row.price));
                            }
//                            listruleList = listRuleModel.rows;
//                            ruleAdapter.setDatas(listruleList);
//                            ruleAdapter.notifyDataSetChanged();
                            packageData();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });
    }

    private void packageData() {
        bottomDialogPackage = new BottomDialog(packageData.size(), this, 1);
        bottomDialogPackage.setChooseTextLisenter(this);
        bottomDialogPackage.setTitle("选择套餐");
        bottomDialogPackage.setBottomTitle("确认");
        bottomDialogPackage.setBottomData(packageData);
    }

    /**
     * 查询停车场的信息
     */
    private void listParkingLot() {
        showLoading();
        OkGo.<String>get(Constant.url + Constant.LISTPARKINGLOT)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        LatlngModule latlngModule = gson.fromJson(response.body(), LatlngModule.class);
                        if (latlngModule.code == 200) {
                            for (LatlngModule.DataBean dataBean : latlngModule.data) {
                                parkingLotData.add(new AbsenceData(dataBean.id, dataBean.name, false));
                            }
                            parkingLotMessage();
                        } else {
                            showToast("没有获取到停车场信息");
                        }
                        stopLoading();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                    }
                });
    }

    private void parkingLotMessage() {
        bottomDialogParkingLot = new BottomDialog(parkingLotData.size(), this, 1);
        bottomDialogParkingLot.setChooseTextLisenter(this);
        bottomDialogParkingLot.setTitle("选择停车场");
        bottomDialogParkingLot.setBottomTitle("添加");
        bottomDialogParkingLot.setBottomData(parkingLotData);
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.choose_time:
                TimeUtil.chooseonYearMonthDayPicker(startTime, this);
                break;
            case R.id.end_time:
                TimeUtil.chooseonYearMonthDayPicker(endTime, this);
                break;
            case R.id.choose_parking:
                type = 2;
                if (parkingLotData != null && parkingLotData.size() > 0) {
//                    bottomDialog.show();
                    bottomDialogParkingLot.show();
                }
                break;
            case R.id.add_parking:
                type = 1;
                //跳转到添加车牌界面
                if (addParkingData.size() > 0) {
                    bottomDialogAddparking.show();
                }
               /* intent = new Intent(this, LicensePlateAddActivity.class);
                intent.putExtra(Constant.MONTHLYSUBSCRIPTION, Constant.MONTHLYSUBSCRIPTION);
                startActivityForResult(intent, 0);*/
                break;
            case R.id.pay_immediate_purchase:
                parkingPlatenumberName = parkingPlatenumber.getText().toString();
                selectPrepayMember();
                break;
            case R.id.check_pay_record:
                intent = new Intent(this, MouthRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.choose_package:
                type = 3;
                if (packageData.size() > 0) {
                    bottomDialogPackage.show();
                }
                break;
        }
    }

    /**
     * 查询月卡的信息
     */
    private void selectPrepayMember() {
        if (TextUtils.isEmpty(parkingPlatenumberName)) {
            showToast("请选择车牌");
            return;
        }
        if (parkinglotId == 0) {
            showToast("请选择停车场");
            return;
        }
        if (packageId == 0) {
            showToast("请选择套餐");
            return;
        }
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("plateNumber", parkingPlatenumberName);
        hashMap.put("parkinglotId", String.valueOf(parkinglotId));
        hashMap.put("startTime", startTime.getText().toString());
        hashMap.put("feeRuleId", String.valueOf(packageId));
        JSONObject jsonObject = new JSONObject(hashMap);
        showLoading();
        OkGo.<String>post(Constant.url + Constant.SELECTPREPAYMEMBER)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        Gson gson = new Gson();
                        payMouthModel = gson.fromJson(response.body(), PayMouthModel.class);
                        if (payMouthModel.code == 200) {
                            bottomDialogPay.show();
                        } else {
                            showToast(payMouthModel.msg);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                        showToast(response.message());
                    }
                });
    }

    @Override
    public void chooseText(AbsenceData text) {
        if (text.text.equals("支付宝") || text.text.equals("微信") /*|| text.text.equals("账户余额")*/) {
            if (text.text.equals("微信")) {
                payWeiXin(payMouthModel.data.outTradeNo);
            } else if (text.text.equals("支付宝")) {
                payAli(payMouthModel.data.outTradeNo);
            } /*else if(text.text.equals("账户余额")){
                accountPay(payMouthModel.data.outTradeNo);
            }*/
        } else if (type == 1) {
            parkingPlatenumber.setText(text.text);
        } else if (type == 2) {
            parkingName.setText(text.text);
            parkinglotId = text.id;
        } else if (type == 3) {
            packageId = text.step;
            parkingPackage.setText(text.text);
            double count = text.month * text.price;
            money.setText(count + "元");
        }
    }

    public void handleMessageMeathed(Message msg) {
        boolean payResponse = payResponse(msg);
        if (payResponse) {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            if (resultCode == Constant.MONTHLYSUBSCRIPTIONPARKING) {
                //获取车牌的名字
                String parkingName = data.getStringExtra(Constant.MONTHLYSUBSCRIPTION_NAME);
                if (!TextUtils.isEmpty(parkingName)) {
                    parkingNameList.add(new AbsenceData(parkingName, false));
                }
            }
        }
    }

    /**
     * 获取分组列表
     */
    public void getGroupList() {
        OkGo.<String>get(Constant.url + Constant.GROUP_LIST_DATA)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        GroupListModule groupListModule = gson.fromJson(response.body(), GroupListModule.class);
                        if (groupListModule.code == 200) {
                            for (GroupListModule.DataBean datum : groupListModule.data) {
                                for (GroupListModule.DataBean.VehiclesBean vehicle : datum.vehicles) {
                                    addParkingData.add(new AbsenceData(vehicle.plateNumber, false));
                                }
                            }
                            addParkingData();
                        } else {
                            showToast(response.message());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                    }
                });
    }

    private void addParkingData() {
        bottomDialogAddparking = new BottomDialog(addParkingData.size(), this, 1);
        bottomDialogAddparking.setChooseTextLisenter(this);
        bottomDialogAddparking.setTitle("选择车牌");
        bottomDialogAddparking.setBottomTitle("添加");
        bottomDialogAddparking.setBottomData(addParkingData);
    }
}
